<template>
  <div>
    <van-nav-bar title="账号登录" left-arrow @click-left="onClickLeft"></van-nav-bar>
    <van-form @submit="onSubmit">
      <van-field  class="inp" v-model="username" placeholder="请输入账号" name="username" :rules="[{ required: true, message: '请填写用户名' },{pattern:/^\w{5,}$/,message:'用户名至少为五位'}]"></van-field>
      <van-field class="inp"  type="password" v-model="password" placeholder="请输入密码" name="password" :rules="[{ required: true, message: '请填写密码' },{pattern:/^\w{6,}$/,message:'密码至少为六位'}]"></van-field>
      <div class="btn" style="margin: 16px;"><van-button block type='info' native-type="submit" >登录</van-button></div>
    </van-form>
    <div class="regiser"><a href="#/register">还没有账号，去注册~</a></div>
  </div>
</template>

<script>
import { userLogin } from '@/api/user'
import { setToken } from '@/utils/storage'

export default {
  name: 'HmLogin',
  data () {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    async onSubmit (values) {
      const res = await userLogin(values)
      if (res.status === 200) {
        setToken(res.body.token)
        this.username = ''
        this.password = ''
        this.$toast.success('登录成功')
        this.$router.push('/my')
      } else if (res.status === 400) {
        this.$toast(res.description)
      }
    },
    onClickLeft () {
      this.$router.back()
    }
  }
}
</script>

<style lang="less" scoped>
.regiser{
  display: flex;

a{
  display: block;
  text-decoration: none;
  color: #3e3d3dc2;margin: auto;
  font-size: 12px;
}
}
.inp{
  margin-top: 20px;
}
</style>
